package cn.caskm.souvenirshopsystem.service.impl;

import cn.caskm.souvenirshopsystem.constants.BizConstants;
import cn.caskm.souvenirshopsystem.domain.Result;
import cn.caskm.souvenirshopsystem.domain.dto.PageDTO;
import cn.caskm.souvenirshopsystem.domain.po.SysBanner;
import cn.caskm.souvenirshopsystem.domain.query.PageQuery;
import cn.caskm.souvenirshopsystem.exceptions.BizException;
import cn.caskm.souvenirshopsystem.mapper.SysBannerMapper;
import cn.caskm.souvenirshopsystem.service.SysBannerService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class SysBannerServiceImpl extends ServiceImpl<SysBannerMapper, SysBanner> implements SysBannerService {

    @Override
    public Result<PageDTO<SysBanner>> page(PageQuery query) {
        // 获取参数
        Long pageNum = query.getPageNum();
        if (pageNum == null) {
            pageNum = BizConstants.DEFAULT_PAGE_NUM;
        }
        Long pageSize = query.getPageSize();
        if (pageSize == null) {
            pageSize = BizConstants.DEFAULT_PAGE_SIZE;
        }

        // 查询数据
        Page<SysBanner> page = lambdaQuery()
                .orderByAsc(SysBanner::getOrderNum)
                .page(new Page<>(pageNum, pageSize));
        
        List<SysBanner> records = page.getRecords();
        return Result.success(PageDTO.of(records, page.getPages(), page.getTotal()));
    }
    
    @Override
    public Result<List<SysBanner>> getAll() {
        List<SysBanner> list = lambdaQuery()
                .orderByAsc(SysBanner::getOrderNum)
                .list();
        return Result.success(list);
    }

    @Override
    public Result<SysBanner> detail(Integer id) {
        SysBanner sysBanner = getById(id);
        if (sysBanner == null) {
            throw new BizException("广告信息不存在");
        }
        return Result.success(sysBanner);
    }

    @Override
    public void saveOrUpdateEntity(SysBanner sysBanner) {
        if (sysBanner.getBanId() == null) {
            // 新增广告
            save(sysBanner);
        } else {
            // 修改广告
            updateById(sysBanner);
        }
    }
}
